<template>
  <div class="order_detail_wrapper">
    <p class="breadcrumb"><router-link :to="{ name: 'orderManage' }" class="bread">订单管理</router-link> <i class="el-icon-arrow-right"></i>订单详情</p>
    <!-- 订单状态 -->
    <div class="order_money">
      <span class="status">{{orderInfosObj | webOrderFilter}}</span>
      <div class="fr all_money">
        <p class="money"> 订单总金额 : <em>{{orderInfosObj.finalAmount| floatPrices}}</em>元</p>
        <p class="money" v-if="(orderInfosObj.payStatus === 0 || orderInfosObj.payStatus === 3) && orderInfosObj.acceptanceAmount > 0"> 待支付金额 : <em>{{orderInfosObj.finalAmount - orderInfosObj.acceptanceAmount | floatPrices}}</em>元</p>
      </div>
      <!-- <p class="font-mid-gray">订单号:{{orderInfosObj.orderId}}</p> -->
    </div>
    <div class="order_step">
      <div class="steps_box">
        <span class="step" :class="{'active': index < stepIndex, 'activelast': index === stepIndex}" v-for="(step, index) in steplist" :key="index">{{step}}</span>
      </div>
    </div>
    <!-- 物流信息 -->
    <section class="order_info_box" v-if="orderInfosObj.deliverStatus === 2 && !orderInfosObj.urgent">
      <div class="order_top">
        <span class="info_title">物流信息</span>
      </div>
      <div class="package_box order_body">
        <div class="package_title" > {{transObj.shipperName}}: {{transObj.logisticCode}} </div>
        <div class="package_status">
          <p v-if="transObj.shipperCode === 'SF'" class="no_trans_info">
            顺丰快递暂不提供物流查询,
            <a class="color-blue" @click.stop  href="http://www.kuaidi100.com" target="_blank">快递查询</a>
          </p>
          <p v-else-if="!transSuccess">
            暂无快递轨迹
            <a class="color-blue" @click.stop href="http://www.kuaidi100.com" target="_blank">快递查询</a>
          </p>
          <template v-else>
            <ul class="status_list">
              <li class="status_list_item" v-for="(item, index) in translist" :key="index" :class="{'latest': index === 0}">
                <span class="date">{{item.acceptTime}}</span>
                <span class="text">{{item.acceptStation}}<span v-if="item.Remark">[{{item.remark}}]</span></span>
              </li>
            </ul>
          </template>
        </div>
      </div>
    </section>
    <!-- 订单详情 -->
    <section class="order_info_box">
      <div class="order_top">
        <span class="info_title">订单信息</span>
        <span class="order-time">下单时间: {{orderInfosObj.createTime}}</span>
      </div>
      <div class="order_body">
        <div class="order_item">
          <p><span class="order_tit">订单号:</span> {{orderInfosObj.orderId}}</p>
          <p><span class="order_tit">收件人:</span> {{receivingInfo.receiver}}</p>
          <p><span class="order_tit">联系方式:</span> {{receivingInfo.receiverMobile}}</p>
          <p><span class="order_tit">收货地址:</span> {{linkAddress}} </p>
        </div>
        <div class="order_item">
          <p><span class="order_tit">支付方式:</span> {{payModeArr[orderInfosObj.payMode]}} - {{payTypeArr[orderInfosObj.payType]}}</p>
          <p><span class="order_tit">快递方式:</span> {{transport.transportName}}</p>
        </div>
      </div>
      <div class="order_bottom">
        <p> <span class="order_head"> 商品总金额:</span> ¥{{orderInfosObj.goodsAmount | floatPrices}}</p>
        <p> <span class="order_head"> 运费:</span> +¥{{transport.freightAmount - orderInfosObj.freightPmtAmount - 0 | floatPrices}}</p>
        <!-- <p v-show="orderInfosObj.acceptanceAmount > 0"> <span class="order_head"> 承兑:</span> ¥{{orderInfosObj.acceptanceAmount | floatPrices}}</p> -->
        <p v-show="orderInfosObj.taxAmount > 0"> <span class="order_head"> 税费:</span> +¥{{orderInfosObj.taxAmount | floatPrices}}</p>
        <p v-show="parseInt(orderInfosObj.activityPmtAmount) > 0"> <span class="order_head"> 活动优惠:</span> -¥{{orderInfosObj.activityPmtAmount | floatPrices}}</p>
        <p v-show="orderInfosObj.voucherAmount > 0"> <span class="order_head"> 抵扣券优惠:</span> -¥{{orderInfosObj.voucherAmount | floatPrices}}</p>
        <p v-show="orderInfosObj.redPacketAmount > 0"> <span class="order_head"> 红包优惠:</span> -¥{{orderInfosObj.redPacketAmount | floatPrices}}</p>
        <p v-show="orderInfosObj.freightPmtAmount > 0"> <span class="order_head"> 运费减免:</span> -¥{{orderInfosObj.freightPmtAmount | floatPrices}}</p>
        <p class="total_price">
          合计 : <em class="total_num">{{orderInfosObj.finalAmount | floatPrices}}</em>元
        </p>
      </div>
      <div class="order_btns_box">
        <span class="btn el-button--danger mar-rt10" v-if="orderInfosObj.orderStatus === 0 && (orderInfosObj.payStatus === 0 || orderInfosObj.payStatus === 3) && (orderInfosObj.payMode === 0 || orderInfosObj.payMode === -1)"
         @click="immediatePay(orderInfosObj)">立即支付</span>

        <span class="btn el-button--danger mar-rt10" 
          @click="uploadPayment" 
          v-if="orderInfosObj.orderStatus === 0 &&  (orderInfosObj.payStatus === 0 || orderInfosObj.payStatus === 3) && orderInfosObj.payMode === 1">
          上传支付凭证</span>

        <span class="btn btn-yellow"
          v-if="orderInfosObj.orderStatus === 0 && (orderInfosObj.payStatus === 0 || orderInfosObj.payStatus === 3) && orderInfosObj.payMode === 1 && !(orderInfosObj.neededInvoice === true && orderInfosObj.finalAmount > 10000)"
          @click="immediatePay(orderInfosObj)">更换支付方式</span>

        <span class='btn btn-yellow' v-if="hasAnother" @click="fetchAnotherOrder(orderInfosObj.orderId)">再次购买</span>
      </div>
    </section>
    <!-- 商品信息 -->
    <section class="order_info_box commdity_box" style="margin-bottom: 80px;">
      <div class="order_top">
        <span class="info_title">商品信息</span>
      </div>
      <div class="order_commondity">
        <!-- 商品信息 :canExchange = "canExchange" -->
        <orderDetailInfo :orderInfosList="orderInfosObj.orderItemPOS" :canExchange = "canExchange" :saleType ="saleType" :orderId="orderId" @setTrack="fetchOrderInfos"></orderDetailInfo>
      </div>
    </section>
    
    <!-- 赠品信息 -->
     <div class=" order_detail_box" v-if="chooseGiftList.length > 0" style="margin-bottom: 80px;">
        <span class="info_title">赠品信息</span>
        <ul class="gift-lists">
          <li class="gift-list-item" v-for="(item, index) in chooseGiftList" :key="index">
            <span class="name">[{{item.brandName}}]{{item.standard}}<em v-show="item.other">—{{item.other}}</em> </span>
            <span class="num">x{{item.num}}</span>
          </li>
        </ul>
      </div>
      <!-- 支付信息  payMode: 0 在线支付 1: 线下支付-->
      <template v-if=" paymentObj !== null && paymentObj !== {}">
        <section class="order_info_box">
          <div class="order_top">
            <span class="info_title">支付信息</span>
            <span class="order-time">支付时间: {{paymentObj.payTime}}</span>
          </div>
          <div class="order_body">
            <div class="order_item">
              <p><span class="order_tit">交易流水号:</span> {{paymentObj.payNo}}</p>
              <p><span class="order_tit" v-if="paymentObj.voucherList !== []">凭证详情:</span>
                <div class="voucher_box" v-for="(payVoucher, index) in paymentObj.voucherList" :key="index">
                  <img v-lazy="prefixImg + payVoucher"/>
                </div>
              </p>
            </div>
            <div class="order_item">
              <p><span class="order_tit">付款方式:</span> {{payModeArr[orderInfosObj.payMode]}}</p>
              <p><span class="order_tit">付款总金额:</span> {{paymentObj.amount}}</p>
            </div>
          </div>
        </section>
      </template>
    <!-- 上传支付凭证 -->
    <el-dialog  title="上传支付凭证" :visible.sync="payVoucherVisi" width="622px" top="20vh"  center>
      <voucher :orderId="orderId" @close="closeVoucherDialog"></voucher>
    </el-dialog>
    <!-- 选择承兑 -->
    <el-dialog title="提示" :visible.sync="showGetMoreMsgVisi" width="450px" >
      <div class="">
       <p class="mar-bt18 ft-16" v-for="(item, index) in getMoreMsg" :key="index">{{item}}</p>
      </div>
      <div class="txt-center" slot="footer">
        <el-button type="primary" @click="handleMoreBtn">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {Breadcrumb, Steps, Step, BreadcrumbItem, Button, Row, Col, Dialog, Form, FormItem, Upload, Input} from 'element-ui'
  import {orderDetailInfo, voucher} from '@/components/index'
  import {getOrderInfos, getTracesInfo, getAnotherOrder} from '@/service/get-data'
  import {payMode, prefixImg, payType} from '@/tool/index'
  import {mapActions, mapState} from 'vuex'
  import {setSession} from '@/config/mUntils'
  export default {
    components: {
      orderDetailInfo,
      elBreadcrumb: Breadcrumb,
      elSteps: Steps,
      elStep: Step,
      elBreadcrumbItem: BreadcrumbItem,
      elButton: Button,
      elRow: Row,
      elCol: Col,
      elDialog: Dialog,
      elForm: Form,
      elFormItem: FormItem,
      elUpload: Upload,
      elInput: Input,
      voucher
    },
    data () {
      return {
        stepIndex: 0, //
        canExchange: false, // 是否可退换货 满足已支付,订单活动
        orderInfosObj: {},
        orderItemPOS: [], // 商品列表数组
        receivingInfo: {}, // 收件信息
        transport: {}, // 配送信息
        deduction: [], // 抵扣券信息数组
        paymentObj: {}, // 支付信息
        payType: '', // 支付状态
        steplist: ['下单', '付款', '备货', '出库', '交易成功'], // 订单状态
        payVoucherVisi: false,
        chooseGiftList: [],
        transState: '',
        translist: [],
        transSuccess: false,
        transObj: {
          // ShipperCode: '圆通快递',
          // LogisticCode: '123456789454684'
        }, // 快递公司 快递单号
        transFlag: false, // 物流只请求一次
        getMoreProductIds: [], // 再来一单成功的规格ID数组
        showGetMoreMsgVisi: false, // 再来一单的弹窗
        getMoreMsg: [] // 再来一单信息展示
      }
    },
    computed: {
      ...mapState({
        acceptanceAmount: state => state.user.acceptanceAmount,
        levelInfoObj: state => state.levelInfoObj
      }),
      orderId () {
        return this.$route.params.orderId
      },
      payModeArr () {
        return payMode
      },
      payTypeArr () {
        return payType
      },
      prefixImg () {
        return prefixImg
      },
      saleType () {
        let refund = this.orderInfosObj.payStatus === 1 && this.orderInfosObj.orderStatus === 0 && this.orderInfosObj.deliverStatus === 0
        let reGoods = this.orderInfosObj.payStatus === 1 && this.orderInfosObj.orderStatus === 0 && (this.orderInfosObj.deliverStatus === 2 || this.orderInfosObj.deliverStatus === 1)
        if (refund) {
          return 'refund'
        } else if (reGoods) {
          return 'reGoods'
        } else {
          return false
        }
      },
      // 红包优惠总额
      redAmount () {
        let amount = 0
        if (JSON.stringify(this.orderInfosObj) === '{}') return
        this.orderInfosObj.unlimitedDeductionVOS.map((item, index) => {
          amount += item.amount
        })
        return amount
      },
      // 代金券优惠总额
      discountAmount () {
        let amount = 0
        if (JSON.stringify(this.orderInfosObj) === '{}') return
        this.orderInfosObj.deduction.map((item, index) => {
          amount += item.amount
        })
        return amount
      },
      // linkAddress 拼接地址
      linkAddress () {
        let district = this.receivingInfo.district || ''
        return this.receivingInfo.province + this.receivingInfo.city + district + this.receivingInfo.address
      },
      hasAnother () {
        return [1, 2].includes(this.orderInfosObj.deliverStatus) || [1, 2, 3, 4].includes(this.orderInfosObj.orderStatus)
      }
    },
    methods: {
      ...mapActions(['getUserLevelInfo']),
      // 再来一单
      async fetchAnotherOrder (orderId) {
        this.getMoreMsg = []
        this.getMoreProductIds = []
        let res = await getAnotherOrder(orderId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          let data = res.data.data
          data.map((item, index) => {
            if (item.msg && !item.success) {
              this.getMoreMsg.push(item.msg)
            }
            if (item.success) {
              this.getMoreProductIds.push(item.productId)
            }
          })
          if (this.getMoreMsg.length) {
            this.showGetMoreMsgVisi = true
          } else {
            this.$router.push({name: 'ShopCart'})
            setSession('getmoreIds', this.getMoreProductIds)
          }
        } else {
          this.$message.error({
            message: res.data.resultMsg
          })
        }
      },
      handleMoreBtn () {
        if (this.getMoreProductIds.length) {
          this.$router.push({name: 'ShopCart'})
          setSession('getmoreIds', this.getMoreProductIds)
        } else {
          this.showGetMoreMsgVisi = false
        }
      },
      // 获取订单列表
      async fetchOrderInfos () {
        let res = await getOrderInfos(this.orderId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data.data
          this.orderInfosObj = res
          this.payType = res.payType
          this.orderItemPOS = res.orderItemPOS
          this.chooseGiftList = res.orderGiftVOS
          this.receivingInfo = res.receivingInfo
          this.transport = res.transport
          this.deduction = res.deduction
          this.paymentObj = res.orderPayVO
          this.orderStep(this.orderInfosObj)
          if (this.transFlag) return
          this.transFlag = true
          if (res.deliverStatus === 2 && !res.urgent) {
            this.fetchWatchTransport()
          }
        } else {
          this.$message({
            message: res.resultMsg,
            type: 'wraming'
          })
        }
      },
      // 立即支付
      immediatePay (orderItem) {
        let amount = orderItem.finalAmount - orderItem.acceptanceAmount
        var limit = false
        if (amount >= 10000) {
          limit = true
        }
        this.$router.push({name: 'Cashier',
          query: {openInvoice: orderItem.hasInvoice, rid: orderItem.orderId, isLimit: limit, totalPrice: amount, payMode: orderItem.payMode, payType: orderItem.payType}})
      },
      // 打开提示窗口alert
      openAlert () {
        let _this = this
        this.$alert('查看此订单的最新的支付状态', '订单状态', {
          confirmButtonText: '确定',
          callback: action => {
            _this.fetchOrderInfos()
          },
          showClose: false
        })
      },
      // 订单step
      orderStep (itemObj) {
        let deliver = itemObj.deliverStatus
        let pay = itemObj.payStatus
        let order = itemObj.orderStatus
        if (deliver === 1 || deliver === 2) {
          this.stepIndex = 3
        } else if (order === 2 || order === 3 || order === 1) {
          this.stepIndex = -1
        } else if (pay === 0 || pay === 3) {
          this.stepIndex = 0
        } else if (pay === 2) {
          this.stepIndex = 0
        } else if (deliver === 0) {
          this.stepIndex = 2
        } else if (order === 4) {
          this.stepIndex = 4
        }
      },
      // 显示上传支付凭证
      uploadPayment () {
        this.payVoucherVisi = true
      },
      // 关闭上传支付凭证
      closeVoucherDialog (value) {
        if (value) {
          this.fetchOrderInfos()
        }
        this.payVoucherVisi = false
      },
      // 查看物流单号
      async fetchWatchTransport () {
        console.log('物流')
        const stateObj = {0: '', 2: '在途中', 3: '已签收', 4: '问题件'}
        this.translist = []
        this.transObj = {}
        let res = await getTracesInfo(this.orderId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          let data = res.data.data
          this.transState = stateObj[data.state]
          if (data.traces && data.traces.length > 0) {
            this.translist = data.traces.reverse()
          }
          this.transSuccess = data.success
          this.transObj['shipperName'] = data.shipperName
          this.transObj['shipperCode'] = data.shipperCode
          this.transObj['logisticCode'] = data.logisticCode
        } else {
          this.$message({
            message: '取消订单失败',
            type: 'wraming'
          })
        }
      }
    },
    watch: {
      orderInfosObj (newVal) {
        let payStatus = newVal.payStatus
        let orderStatus = newVal.orderStatus
        payStatus === 1 && orderStatus === 0 ? this.canExchange = true : this.canExchange = false
      }
    },
    mounted () {
      !this.levelInfoObj.purchaserId && this.getUserLevelInfo() // 不存在会员等级 重新请求
      this.fetchOrderInfos()
    },
    filters: {
      webOrderFilter (itemObj) {
        let deliver = itemObj.deliverStatus
        let pay = itemObj.payStatus
        let order = itemObj.orderStatus
        if (deliver === 1 || deliver === 2) {
          // this.stepsIndex = 3
          return '已发货'
        } else if (order === 2 || order === 3 || order === 1) {
          // this.stepsIndex = 5
          return '已关闭'
        } else if (pay === 0) {
          // this.stepsIndex = 0
          return '待支付'
        } else if (pay === 2) {
          // this.stepsIndex = 0
          return '待审核'
        } else if (deliver === 0) {
          // this.stepsIndex = 2
          return '待发货'
        } else if (order === 4) {
          // this.stepsIndex = 4
          return '已结束'
        }
      }
    }
}
</script>

<style lang='scss' scoped>
  .bread{
      &:hover{
        color:#ffcc00;
      }
    }
  .order_money{
    display: inline-block;
    width: 100%;
    line-height: 28px;
    margin-top: 5px;
    .status{
      @include fontbase(#FF7300,20px);
      vertical-align: bottom;
    }
    .all_money{
      font-size: 14px;
      color: #858585;
    }
    .money{
      margin-right: 32px;
      em{
        font-size: 20px;
        color:#FF7300;
      }
    }
  }
  
  .order_step{
    background: #FFF8F3;
    border-top:1px solid #FF7300;
    padding: 30px 20px;
    margin-top: 14px;
    margin-bottom: 28px;
    .steps_box{
      display: flex;
      justify-content: space-between;
      background: #F6E6DB;
      border-radius: 100px;
      height:20px;
      line-height: 20px;
      overflow: hidden;
    }
  }
  .steps_box{
      span{
        flex:1;
        text-align: center;
        font-size: 12px;
        color: #C89973;
        &.active{
          background: #FF7300;
          color: #ffffff;
        }
        &.activelast{
          background: #FF7300;
          color: #ffffff;
          border-top-right-radius: 100px;
          border-bottom-right-radius: 100px;
        }
      }
    }
  .info_title{
    display: inline-block;
    @include fontbase(#333333, 18px, 25px);
    font-weight: 545;
    margin-bottom: 18px;
  }
    .order_detail_box{
      @include border_bt();
      .des{
        margin-top: 20px;
      }
      .order_detail{
        font-size: 16px;
        color: #666666;
        padding-bottom: 16px;
        .tit{
          min-width: 85px;
          display: inline-block;
        }
      }
    }
  .order_detail li{
    line-height: 22px;
    margin-bottom: 9px;
  }
  .voucher_box{
    display: inline-block;
    vertical-align: top;
    // padding-left: 24px;
    img{
      width: 120px;
      border:1px solid #cdcdcd;
      margin-right: 15px;
    }
  }
  .voucher_edit{
      vertical-align: bottom;
      color:#2A91D2;
      font-size: 14px;
      cursor: pointer;
    }
  .order_result_box{
    text-align: right;
    color: #666666;
    padding-top: 20px;
    .des{
      // margin-top: 30.7px;
      line-height: 28px;
    }
    .disting{
      color: #e0dfdf;
    }
    
    .btn_submit{
      width: 300px;
      height: 50px;
    }
  }

  .btn-handle{
    height: 35px;
    padding: 7px 50px;
    font-size: 16px;
    color: #FFFFFF;
    background: #FF7300;
    border-radius: 4px;
    cursor: pointer;
  }
  .gift-lists{
    margin-bottom: 20px;
    padding-right: 305px;
    .gift-list-item{
      display: inline-block;
      border-radius: 4px;
      border: solid 1px #dcdcdc;
      padding: 12px 10px 10px 10px;
      color: #555555;
      font-size: 0;
      line-height: 1;
      margin-right: 20px;
      margin-bottom: 10px;
      margin-top: 10px;
      .name{
        font-size: 16px;
      }
      .num{
        color: #f45923;
        margin-left: 14px;
        font-size: 14px;
      }
      .gift-list-close{
        color: rgba(0, 0, 0, 0.3);
        margin-left: 20px;
        font-size: 16px;
        cursor: pointer;
        &:hover{
          color: rgba(0, 0, 0, 0.4);
        }
      }
    }
  }
  // 新改的订单详情
  .order_info_box{
    position: relative;
    margin-bottom: 28px;
    padding-bottom: 20px;
    &.commdity_box{
      border-bottom: none;
      padding-bottom: 0;
    }
  }
  .order_top{
    // background: #e7e7e7;
    // padding: 8px 15px;
    font-size: 14px;
    line-height: 2;
    color: #898989;
    .order-time{
      float:right;
      color:#666666;
      font-size:15px;
    }
  }
  .order_body{
    overflow: hidden;
    // justify-content: flex-start;
    padding: 15px 0;
    border-top: 1px solid #dcdcdc;
    border-bottom: 1px solid #dcdcdc;
    // margin: 0 30px 0 20px;
    line-height: 22px;
    color: #666666;
    .order_item{
      float: left;
      width: 50%;
      p{
        margin-bottom: 10px;
      }
    }
    .order_tit{
      display: inline-block;
      // width: 70px;
    }
  }
  .order_bottom{
    padding: 15px 40px;
    line-height: 30px;
    text-align: right;
    color: #333;
    .order_head{
      color:#666;
    }
  }
  .total_price{
      font-size: 24px;
      line-height: 33px;
      margin-top: 13px;
      margin-bottom: 42px;
      color:#666;
      em{
        font-style: normal;
        font-size: 36px;
        color: #F55923;
      }
    }
  .order_btns_box{
    text-align: right;
    padding-right: 40px;
  }
  .btn{
    display: inline-block;
    margin-bottom: 5px;
    width: 140px;
    height:35px;
    line-height: 35px;
    text-align: center;
    border-radius: 4px;
    font-size: 16px;
        cursor: pointer;
  }
  .btn-yellow{
    background: #FFDE00;
    color: #6B6B6B;
  }
  .package_box{
    // background-color: #f3f3f3;
    margin-bottom: 32px;
    position: relative;
    // border-radius: 3px;
    .package_title{
      font-size: 18px;
      padding: 14px 0 14px 20px;
    }
    .package_status{
      padding: 18px 0 0 20px;
    }
    .status_list{
      margin: 0;
      padding: 0;
      margin-left: 12px;
      margin-top: -9px;
      padding-left: 10px;
      list-style: none;
      font-size: 12px;
    }
    .no_trans_info{
      color: #ff6000;
    }
    .status_list_item{
      // margin-bottom: -2px;
      height: auto;
      min-height: 30px;
      border-left: 1px solid #d9d9d9;
      &:last-child{
        border:none;
      }
      &:before{
        content: '';
        border: 3px solid #f3f3f3;
        background-color: #d9d9d9;
        display: inline-block;
        width: 5px;
        height: 5px;
        border-radius: 5px;
        margin-left: -6px;
        margin-right: 10px;
      }
      .date{
        font-weight: 700;
        margin-right: 8px;
        font-family: Arial;
      }
      .text{
        display: inline-block;
        vertical-align: text-top;
        line-height: 1.3em;
      }
    }
    .latest{
      &:before{
        background-color: #fe4300;
        border-color: #f8e9e4;
      }
    }
  }
</style>
